import os, subprocess, shutil, multiprocessing

def run_scenario(exe_file, scen_file): 
    # get the output directory 
    f = open(scen_file,'r')
    f.readline(); 
    thedir = f.readline().split('\t')[1]; 
    f.close() 
    
    # make dirs 
    if not os.path.exists(thedir): 
        os.makedirs(thedir)
    
    # copy executable to thedir
    bindir = os.path.dirname(exe_file)
    newbindir = os.path.join(thedir, 'bin')
    new_exe_file = os.path.join(newbindir, os.path.basename(exe_file))
    if os.path.exists(newbindir): 
        shutil.rmtree(newbindir)
    shutil.copytree(bindir, newbindir)
    
    # copy the scenario file over 
    new_scen_file = os.path.join(thedir, os.path.basename(scen_file))
    shutil.copy2(scen_file, new_scen_file)
    
    # run it! 
    print 'Running {0}'.format(new_exe_file)
    subprocess.call([new_exe_file,new_scen_file,str(max(1,multiprocessing.cpu_count()-1))])
    
    
if __name__ == '__main__': 
    try: 
        run_scenario(r'..\ModsimOptimizationTester\bin\x86\Release\iwpmtester.exe', 'taylor.gcwind')
    except Exception as e: 
        print e
    raw_input('Press Enter to continue...')